import Express from "express";
import { MoiveService } from "../services/MovieService";
import { ResponseHelper } from "./ResponseHelper";

const router = Express.Router();

// 根据id查询一个电影
router.get("/:id", async (req, res) => {
  try {
    const { id } = req.params;
    const movie = await MoiveService.findById(id);

    ResponseHelper.sendData(movie, res);
  } catch (error) {
    ResponseHelper.sendData(null, res);
  }
});

// 根据query消息page，limit查询多个电影
router.get("/", async (req, res) => {
  try {
    const result = await MoiveService.find(req.query as any);
    ResponseHelper.sendPageData(result, res);
  } catch (error) {
    ResponseHelper.sendData(null, res);
  }
});

// 新增一个电影
router.post("/", async (req, res) => {
  try {
    const result = await MoiveService.add(req.body);
    if (Array.isArray(result)) {
      ResponseHelper.sendError(result, res);
    } else {
      ResponseHelper.sendData(result, res);
    }
  } catch (error) {
    ResponseHelper.sendData(null, res);
  }
});

// 根据id修改电影
router.put("/:id", async (req, res) => {
  try {
    const { id } = req.params;
    const result = await MoiveService.edit(id, req.body);
    if (Array.isArray(result)) {
      ResponseHelper.sendError(result, res);
    } else {
      ResponseHelper.sendData(true, res);
    }
  } catch (error) {
    ResponseHelper.sendData("id错误", res);
  }
});

// 根据id删除某个电影
router.delete("/:id", async (req, res) => {
  try {
    const { id } = req.params;
    await MoiveService.delete(id);
    ResponseHelper.sendData(true, res);
  } catch (error) {
    ResponseHelper.sendData("id错误", res);
  }
});

export default router;
